import { Elysia } from 'elysia';

import { config } from '@/config';
import { getServerUrls } from '@/config/utils';
import { accessLoggerMiddleware } from '@/middleware/access-logger';
import { errorWrapperMiddleware } from './middleware/error-wrapper';
import { createCorsConfig, createOpenapiConfig, createOpenTelemetryConfig } from '@/plugins';
import { apiRoutes } from '@/routes/api';
import { gracefulShutdown } from '@/utils/graceful-shutdown';
import { logger } from '@/utils/logger';

export const app = new Elysia({
  name: config.APP_NAME,
})
  .use(createCorsConfig())
  .use(createOpenapiConfig())
  .use(createOpenTelemetryConfig())
  .use(accessLoggerMiddleware)
  .use(errorWrapperMiddleware)
  .use(apiRoutes);

// 如果直接运行此文件则启动服务器
if (import.meta.main) {
  // 设置优雅关闭
  app.on('stop', async () => {
    logger.info('🛑 正在关闭服务器...');
    await gracefulShutdown();
  });
  process.on('beforeExit', app.stop.bind(app));
  process.on('SIGINT', app.stop.bind(app));
  process.on('SIGTERM', app.stop.bind(app));

  app.listen(config.LISTEN_PORT);

  const urls = getServerUrls();
  logger.info({
    ...urls,
    msg: '🚀 服务器启动成功',
  });
  if (config.OPENAPI_ENABLED) {
    logger.info({
      listen: `${urls.listen}${config.OPENAPI_PATH}`,
      advertise: `${urls.advertise}${config.OPENAPI_PATH}`,
      msg: '📋 OpenAPI 接口',
    });
  }
}
